//ajax request holders 
var newItemsAjax, newItemAjax, updatedItemsDetails;
// const strings
var NEWITEMS = "newItems", SEARCHEDITEMS = "searchedItems";
// holds the item when the view item page is being displayed(otherwise its null)
var selectedItem;
// selected items
var searchedItems;
// store the newest items
var newItemsArr = [];
// store the publish time of the most new item we are showing
var lastItemPublishTime;

// gets new items from the server
function getNewItems() {
	var url = addTimeToURL("NewItems", lastItemPublishTime);
	newItemsAjax = fire("GET", url, new Object(), newItemsListener);
}

// stores the new items in the server as well as it calls the UI updater
function newItemsListener() {
	var obj = validResponse(newItemsAjax);
	if (obj == undefined || obj.items == undefined) return;
		// since the items are sorted according to publish time we use
		// newItemsArr as
		for ( var i = obj.items.length - 1; i > -1; i--) {
			newItemsArr.unshift(obj.items[i]);
			lastItemPublishTime = obj.items[i].publishTime;
			
		}
		if (newItemsArr.length > 4)
			newItemsArr.length = 4;
		fetchNewItems(obj.items.length, newItemsArr);
	
}

var newItemsCheckingInterval, updatingItemsInterval;

function startRefreshingItems() {
	// every 5 seconds check for new items
	getNewItems();
	newItemsCheckingInterval = setInterval(getNewItems, 5000);
	// every 5 seconds ask for new details of the items
	// start after checking for new items in 2.5 second to avoid bugs
	setTimeout(function() {
		syncItemsDetails();
		updatingItemsInterval = setInterval(syncItemsDetails, 5000);
	}, 2500);

}

startRefreshingItems();

function stopRefreshingItems() {
	clearInterval(newItemsCheckingInterval);
	clearInterval(updatingItemsInterval);
}

// posting a new item
function newItem(params) {
	newItemAjax = fire("POST", "Items", params, postItemListener);
}

function postItemListener() {
	var obj = validResponse(newItemAjax);
	if (obj != undefined) {
		if (obj.result == true) {
			reStorePage();
		} else {
			showError(obj.errorMessage);
		}
	}
}

// modify the time left for each item
function updateTimeLeft() {
	// apply for new items
	iterateOverItems(newItemsArr);
	// apply for searched items
	iterateOverItems(searchedItems);
	// apply for the selected item
	if (selectedItem != null) {
		iterateOverItems([ selectedItem ]);
	}
}

function iterateOverItems(items) {
	if (items != null)
		for ( var i = 0; i < items.length; i++) {
			var item = items[i];
			var timeLeft = item.sellTime - new Date().getTime();
			timeLeft <= 0 ? 0 : timeLeft;
			item.timeLeft.setTime(timeLeft);
		}
}

// sends all the stored items in an array to the server
function syncItemsDetails() {
	var items = new Array();
	items = items.concat(newItemsArr);
	if (searchedItems != null) {
		items = items.concat(searchedItems);
	}
	if (selectedItem != null) {
		items = items.concat(selectedItem);
	}
	for ( var i = 0; i < items.length; i++) {
		if (items[i] == null) {
			items.splice(i--, 1);
		} else
			items[i] = items[i].id;
	}
	if(items.length < 1)
		return;
	var url = "Items?itemsToUpdate=" + JSON.stringify(items);
	updatedItemsDetails = fire("GET", url, new Object(),
			syncItemsDetailsListener);
}

// synchronize current
var lastSyncItemIndex;
var syncItems;

function syncItemsDetailsListener() {
	var obj = validResponse(updatedItemsDetails);
	if (obj != undefined && obj.updatedItems.length != null) {
		syncItems = obj.updatedItems;
		lastSyncItemIndex = 0;
		copySyncItems(newItemsArr);
		copySyncItems(searchedItems);
		copySyncItems([ selectedItem ]);
		updateItemsDetails();
	}
}

function copySyncItems(items) {
	if (items != null) {
		for ( var i = 0; i < items.length; i++) {
			if (items[i] == null) {
				continue;
			}
			items[i].currentBidAmount = syncItems[lastSyncItemIndex].currentBidAmount;
			items[i].winnerUserName = syncItems[lastSyncItemIndex].winnerUserName;
			lastSyncItemIndex++;
		}
	}
}

function getCachedNewItems() {
	return newItemsArr;
}

// except new item arr
function emptyCachedItems() {
	selectedItem = null;
	searchedItems = null;
}


